package com.linln.agent.store;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.linln.common.utils.JsonUtils;
import com.linln.modules.message.domain.MessageType;
import com.linln.modules.store.domain.Type;
import com.linln.modules.store.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.linln.common.constant.AdminConst;
import com.linln.common.constant.NoticeTypeConst;
import com.linln.common.constant.UrlConst;
import com.linln.common.utils.MoneyUtils;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.domain.MemberRefund;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberInfoService;
import com.linln.modules.member.service.MemberOrderService;
import com.linln.modules.member.service.MemberRefundService;
import com.linln.modules.message.domain.MessageInfo;
import com.linln.modules.store.domain.Storeinfo;
import com.linln.modules.store.service.StoreinfoService;
import com.linln.modules.system.domain.Area;
import com.linln.modules.system.service.AreaService;

/**
 * @author hct
 * @date 2019/09/12
 */
@Controller
@RequestMapping("agent/store")
public class AgentStoreController {

    @Autowired
    private StoreinfoService baseinfoService;
    @Autowired
    private MemberAgentService agentService;
    @Autowired
    private MemberInfoService memberService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private MemberRefundService refundService;
    @Autowired
    private TypeService typeService;

    @Autowired
    private MemberOrderService orderService;
    private static final String REFUND_SUCCESS = "SUCCESS";
    /**
     * 所有商户列表页面
     */
    @GetMapping("/index")
    public String index(Model model, Storeinfo baseinfo,Long typeId,HttpServletRequest request) {
        ExampleMatcher matchertype = ExampleMatcher.matching();
        // 获取部门列表
        Type type=new Type();
        Example<Type> exampleType = Example.of(type, matchertype);
        Sort sort = new Sort(Sort.Direction.ASC, "num");
        List<Type> typealllist = typeService.getListByExample(exampleType, sort);


        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("store_name", match -> match.contains());
        baseinfo.setStoreStatus(1);
       // MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
        
        baseinfo.setArea(agent.getArea());
        if(typeId!=null && typeId.longValue()>0) {
            Type typenew=new Type();
            typenew.setId(typeId);
            baseinfo.setStoretype(typenew);
        }
        // 获取数据列表
        Example<Storeinfo> example = Example.of(baseinfo, matcher);
        Page<Storeinfo> list = baseinfoService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("typelist", typealllist);
        model.addAttribute("page", list);
        return "/agent/store/index";
    }
    
    /**
     * 所有置顶列表页面
     */
    @GetMapping("/topindex")
    public String topindex(Model model, Storeinfo baseinfo,HttpServletRequest request) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("store_name", match -> match.contains());
        baseinfo.setStoreStatus(1);
        baseinfo.setIstop(1);
        baseinfo.setPayStatus(1);
        //MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
        
        baseinfo.setArea(agent.getArea());        
        // 获取数据列表
        Example<Storeinfo> example = Example.of(baseinfo, matcher);
        Page<Storeinfo> list = baseinfoService.getPageList(example);
        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/agent/store/topindex";
    }
    
    /**
     * 待审核列表页面
     */
    @GetMapping("/shenheindex")
    public String shenheindex(Model model, Storeinfo baseinfo,HttpServletRequest request) {

    	// 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("store_name", match -> match.contains());
        baseinfo.setStoreStatus(0);
        //baseinfo.setIstop(1);  
        //baseinfo.setPayStatus(1);
        //MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
        
        baseinfo.setArea(agent.getArea());        
        // 获取数据列表
        Example<Storeinfo> example = Example.of(baseinfo, matcher);
        Page<Storeinfo> list = baseinfoService.getPageList(example);
        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/agent/store/shenheindex";
    }
    /**
     * 跳转到编辑页面
     */
    @GetMapping("/toshenhe/{id}")
     public String toEdit(@PathVariable("id") Storeinfo baseinfo, Model model) {
        model.addAttribute("baseinfo", baseinfo);
        return "/agent/store/toshenhe";
    }
    
   /* *//**
     * 审核
     * @param model
     * @param id
     * @param storestatus  0待审核 1同意 2拒绝
     * @param request
     * @return
     *//*
    @PostMapping("/shenheStore")
    @ResponseBody
    public ResultVo save(Long id ,Integer storeStatus,HttpServletRequest request) {
        // 复制保留无需修改的数据
    	Storeinfo store=baseinfoService.getById(id);
    	//MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
         
    	if(baseinfoService.updateStoreStatus(storeStatus, id)) {
    		if(storeStatus.intValue()==1) {
            	//同意的时候将钱增加到代理商的余额中
            	MemberAgent agentnew=agentService.getById(agent.getId());
            	//代理商拿一个比例的折扣，其他的归属公司
            	if(store.getFee().compareTo(0D)>0){
            		Double curagentmoney=MoneyUtils.mul(store.getFee(),0.9);
                	agentnew.setAllmoney(MoneyUtils.add(agentnew.getAllmoney(), curagentmoney));
                	agentnew.setCurmoney(MoneyUtils.add(agentnew.getCurmoney(),curagentmoney));                		
                	agentService.save(agentnew);
                	MemberInfo memberinfo=memberService.getById(agent.getId());
                	memberinfo.setAllmoney(MoneyUtils.add(memberinfo.getAllmoney(), curagentmoney));
                	memberinfo.setMoney(MoneyUtils.add(memberinfo.getMoney(), curagentmoney));           	
                	memberService.save(memberinfo);
            	}
            	
            }else if(storeStatus.intValue()==2) {
            	
            	if(store.getIstop()==1) {
            		//拒绝的时候将费用退回给客户
               	 //申请退款
                   WxPayRefundRequest refundInfo = WxPayRefundRequest.newBuilder()
                           //订单号
                           .outTradeNo(store.getOrderId())
                           //退款订单号
                           .outRefundNo(ToolUtil.getRandomString(16)) 
                           //金额
                           .totalFee(yuanToFee(new BigDecimal(store.getFee())))
                           //退款金额
                           .refundFee(yuanToFee(new BigDecimal(store.getFee())))
                          
                           //todo 回调地址
                           .notifyUrl(UrlConst.REFUNDNOTICEURL)
                           .build();
                   WxPayRefundResult wxPayRefundResult;
                   try {
                       wxPayRefundResult = wxPayService.refund(refundInfo);
                       //判断退款信息是否正确
                       if (REFUND_SUCCESS.equals(wxPayRefundResult.getReturnCode())
                               && REFUND_SUCCESS.equals(wxPayRefundResult.getResultCode())) {
                       	saveRefund(store,agent.getId());
                        }
                   } catch (WxPayException e) {
                   	return ResultVoUtil.error("异常");
                   }	
            	}else {
                   	saveRefund(store,agent.getId());

            	}
            	
            }
            return ResultVoUtil.success("审核成功");
        	}else {
        		return ResultVoUtil.error("审核失败");
        	}
     }*/
    
    
    /**
     * 下架  置顶的地方退款
     * @param model
     * @param id    
     * @param storestatus  0待审核 1同意 2拒绝
     * @param request
     * @return
     */
    @RequestMapping("/refundStore")
    @ResponseBody
    public ResultVo refundStore(Long id ,HttpServletRequest request) {
        // 复制保留无需修改的数据
    	Storeinfo store=baseinfoService.getById(id);
    	//MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
         
    	if(baseinfoService.updateStoreStatus(2, id)) {
            	if(store.getIstop()==1 && store.getFee().doubleValue()>0) {
            		//拒绝的时候将费用退回给客户
               	 //申请退款
                   WxPayRefundRequest refundInfo = WxPayRefundRequest.newBuilder()
                           //订单号
                           .outTradeNo(store.getOrderId())
                           //退款订单号
                           .outRefundNo(ToolUtil.getRandomString(16)) 
                           //金额
                           .totalFee(yuanToFee(new BigDecimal(store.getFee())))
                           //退款金额
                          .refundFee(yuanToFee(new BigDecimal(store.getFee())))
                          
                           //todo 回调地址
                           .notifyUrl(UrlConst.REFUNDNOTICEURL)
                           .build();
                   WxPayRefundResult wxPayRefundResult;
                   try {
                       wxPayRefundResult = wxPayService.refund(refundInfo);
                       //判断退款信息是否正确
                       if (REFUND_SUCCESS.equals(wxPayRefundResult.getReturnCode())
                               && REFUND_SUCCESS.equals(wxPayRefundResult.getResultCode())) {
                       	saveRefund(store,agent.getId());
                       	MemberAgent agentnew=agentService.getById(agent.getId());
                     	agentnew.setAllmoney(MoneyUtils.sub(agentnew.getAllmoney(), store.getFee()));
                    	agentnew.setCurmoney(MoneyUtils.sub(agentnew.getCurmoney(),store.getFee()));
                    	agentService.save(agentnew);
              		    orderService.updateRefundStatus(store.getOrderId());

                        }
                   } catch (WxPayException e) {
                   	return ResultVoUtil.error("异常");
                   }	
            	}else {
                   	saveRefund(store,agent.getId());

            	}
            	
            
            return ResultVoUtil.success("审核成功");
        	}else {
        		return ResultVoUtil.error("审核失败");
        	}
     }
    
    
    public void saveRefund(Storeinfo store,Long agentId) {
    	MemberRefund refund=new MemberRefund();
    	refund.setAgentId(agentId);
    	refund.setArea(store.getArea());
    	refund.setContent("拒绝用户创建商户");
    	refund.setMoney(store.getFee());
    	refund.setOrderCode(store.getOrderId());
    	refund.setRefundmoney(store.getFee());
    	refund.setRefundStatus(0);
    	refund.setType(NoticeTypeConst.STORE);
    	refund.setTypeId(store.getId());
    	refundService.save(refund);
    }
    
    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
     public String toEditnew(@PathVariable("id") Storeinfo baseinfo, Model model) {
        model.addAttribute("baseinfo", baseinfo);
        return "/agent/store/edit";
    }
    
    /**
     * 审核
     * @param model
     * @param id
     * @param storestatus  0待审核 1同意 2拒绝
     * @param request
     * @return
     */
    @PostMapping("/editStoreStar")
    @ResponseBody
    public ResultVo editStoreStar(Long id ,Integer readnum,Integer storeStar,HttpServletRequest request) {
	        // 复制保留无需修改的数据
	    	//Storeinfo store=baseinfoService.getById(id);
 	    	baseinfoService.updateStoreStar(storeStar,readnum, id);
        ResultVo resultVo = ResultVoUtil.success("修改成功");
        return resultVo;
        	
     }
    
    
    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    public String toDetail(@PathVariable("id") Storeinfo baseinfo, Model model) {
        model.addAttribute("baseinfo",baseinfo);
        return "/agent/store/detail";
    }


    /**
     * 1 块钱转为 100 分
     * 元转分
     *
     * @param bigDecimal 钱数目
     * @return 分
     */
    private int yuanToFee(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }

    /**
     * 时间
     *
     * @return 时间戳
     */
    private String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}